package jgs1904.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MyController {

    // 声明单元方法:跳转登录页面
    @RequestMapping("login")
    public String loginPage() {
        return "login";
    }


    // 声明单元方法:跳转主页面
    @RequestMapping("main")
    public String getMainPage() {
        return "main";
    }


    // 声明单元方法：用户登录
    @RequestMapping("userLogin")
    public String userLogin(String uname, String pwd, @RequestParam(defaultValue = "false") Boolean remember) {
        // 获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        // 创建对象存储认证信息
        // 添加第三个参数，表示是否启用rememberme功能
        AuthenticationToken token = new UsernamePasswordToken(uname, pwd, remember);
        // 调用Shiro的login方法完成登录认证
        try {
            // login()方法没有返回值，只能通过是否有异常判断是否登录成功。
            subject.login(token);
            return "redirect:/main";
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
            return "账号不存在";
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            return "密码错误";
        }
    }

}
